package com.warm.androidstudy.utils;

import android.net.Uri;


import com.warm.androidstudy.config.AppConfig;
import com.warm.androidstudy.constant.SConstant;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.zhy.http.okhttp.callback.Callback;


/**
 * by admin on 2017/7/5.
 */
public class HttpWebUtil {

    private static final String REQUEST_PARAMETER = "parameter";
    private static final String REQUEST_CONTENT_PRE = "&" + REQUEST_PARAMETER + "=";
    private static final String REQUEST_CONTENT = "content";
    private static final String MEDIA_TYPE_JSON = "application/json;charset=utf-8";


    /**
     * 上传单个文件
     *
     * @param url
     * @param file
     * @param callback
     */
    public static void postFile(String url, File file, Callback callback) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Disposition", "form-data; name=\"" + "attachment"
                + "\"; filename=\"" + Uri.encode(file.getName()) + "\"");
        String formKeyName = "attachment"; // 即类别表单中<input type="file" name="mFile"/>的name属性

        OkHttpUtils.post()
                .addFile(formKeyName, file.getName(), file)
                .url(url)
                .addHeader("Commons-Session", AppSPUtils.getCurrentUID())
                .addHeader("App-Code", SConstant.appCode)
                .addHeader("Content-Type", SConstant.contentType)
                .headers(headers)
                .build()
                .connTimeOut(AppConfig.HTTP_CONNECT_TIMEOUT)
                .readTimeOut(AppConfig.HTTP_REQUEST_TIMEOUT)
                .writeTimeOut(AppConfig.HTTP_UPLOAD_TIMEOUT)
                .execute(callback);
    }

    /**
     * 初始化https(忽略证书)
     */
    public static final void initHttps() {
        SSLContext sc;
//        OkHttpUtils.getInstance().getOkHttpClient().networkInterceptors().add(new StethoInterceptor());
        try {
            sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new MyTrustManager()}, new SecureRandom());
//            OkHttpUtils.getInstance().getOkHttpClient().setHostnameVerifier(new MyHostnameVerifier()).setSslSocketFactory(sc.getSocketFactory());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
    }

    private static class MyHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }

    }

    private static class MyTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)

                throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }
    }

    private static boolean URL_exists = true;

    // 判断一个url是否有效
    public static boolean checkIfUrlExists(final String URLName) {
        URL_exists = false;
        try {
            //设置此类是否应该自动执行 HTTP 重定向（响应代码为 3xx 的请求）。
            HttpURLConnection.setFollowRedirects(false);
            //到 URL 所引用的远程对象的连接
            HttpURLConnection con = (HttpURLConnection) new URL(URLName)
                    .openConnection();
            /* 设置 URL 请求的方法， GET POST HEAD OPTIONS PUT DELETE TRACE 以上方法之一是合法的，具体取决于协议的限制。*/
            con.setRequestMethod("HEAD");
            con.setConnectTimeout(6000);
            con.setReadTimeout(6000);
            //从 HTTP 响应消息获取状态码
            // LogUtil.e("ryan","head "+con.getResponseCode());
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                URL_exists = true;
            } else {
                URL_exists = false;
            }
        } catch (Exception e) {
            return URL_exists = false;
        }
        return URL_exists;
    }
}
